/**
 *    Copyright (c) 2021 WANGFEIHU
 *    SSO-PLUS is licensed under Mulan PSL v2.
 *    You can use this software according to the terms and conditions of the Mulan PSL v2.
 *    You may obtain a copy of Mulan PSL v2 at:
 *             http://license.coscl.org.cn/MulanPSL2
 *    THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 *    See the Mulan PSL v2 for more details.
 */
package cn.codinglives.ssoplus.controller;

import cn.codinglives.ssoplus.entity.SsoMain;
import cn.codinglives.ssoplus.jwt.TokenUser;
import cn.codinglives.ssoplus.service.JwtService;
import cn.codinglives.ssoplus.service.SsoMainService;
import cn.codinglives.ssoplus.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * 用于oauth2 sso login.
 * @author feihu.wang
 */
@Controller
public class Auth2Controller {

	private static final Logger LOG = LoggerFactory
			.getLogger(Auth2Controller.class);



	@Resource
	private SsoMainService ssoConfService;

	@Resource
	private UserService userService;

	@Resource
	private JwtService jwtService;

	/**
	 *
	 * @param code
	 * @param state
	 * @return
	 */
	@RequestMapping(value = "/auth2/back", method = RequestMethod.GET)
	public ResponseEntity oauthBack(@RequestParam String code, @RequestParam String state) {
		TokenUser user = null;
		String url = "";
		String accessToken = null;
		try {
			List<SsoMain> ssoConfList = ssoConfService.list("");
			for (SsoMain conf : ssoConfList) {
				if (conf.getTenantCode().equalsIgnoreCase(state)) {
					user = userService.getUserInfo("");
					url = conf.getSsoUrl();
					 break;
				}
			}
			if (user == null) {
				return ResponseEntity.status(HttpStatus.FORBIDDEN).body("用户信息未同步！");
			}
			accessToken = jwtService.createToken(user.getUserId());
			url = url  + "?token=" + accessToken;
			return ResponseEntity.status(HttpStatus.FOUND).location(URI.create(url)).build();
		} catch (Exception e) {
			LOG.error("sso-auth-error", e);
		}
		return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("登录失败，检查日志");
	}

}
